package org.cn.osiris.user.service.impl;

import org.cn.osiris.basic.domain.VerifyCodeConstants;
import org.cn.osiris.basic.exception.BusinessException;
import org.cn.osiris.basic.util.Md5Utils;
import org.cn.osiris.basic.util.StrUtils;
import org.cn.osiris.user.domain.Logininfo;
import org.cn.osiris.user.domain.User;
import org.cn.osiris.user.domain.UserDto;
import org.cn.osiris.user.mapper.LogininfoMapper;
import org.cn.osiris.user.mapper.UserMapper;
import org.cn.osiris.user.service.IUserService;
import org.cn.osiris.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 手机号注册
     * @param userDto
     */
    @Override
    public void phoneRegister(UserDto userDto) {
        String phone = userDto.getPhone();
        String phoneCode = userDto.getPhoneCode();
        String pwd = userDto.getPassword();
        String confirmPwd = userDto.getPasswordRepeat();

        System.out.println(pwd);
        System.out.println(confirmPwd);
        System.out.println(phoneCode);
        //校验
        //校验空值
        if (StringUtils.isEmpty(phone)
            || StringUtils.isEmpty(phoneCode)
            || StringUtils.isEmpty(pwd) ){
            throw new BusinessException("请输入正确的数据");
        }
        //检验密码是否相等
        if (!pwd.equals(confirmPwd)){
            throw new BusinessException("两次密码不一致");
        }

        //校验验证码是否过期
        Object obj = redisTemplate.opsForValue().get(VerifyCodeConstants.REGISTER_CODE_PREFIX + phone);
        System.out.println(obj);
        if (obj == null){
            throw new BusinessException("验证码无效，请重新获取！！！");
        }
        //校验验证码是否正确
         String codeTmp = obj.toString().split(":")[0];
        if (!codeTmp.equalsIgnoreCase(phoneCode)){
            throw  new BusinessException("验证码错误");
        }


        //保存数据
        //先保存t_longinfo
        //获取user和logininfo对象
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);
        //手机注册数据校验后，直接开启启用状态（邮箱需要邮件激活后进行状态修改）
        user.setState(1);
        logininfo.setDisable(true);

        System.out.println("****user*****"+user);
        System.out.println("****logininfo*****"+logininfo);

        logininfoMapper.add(logininfo);
        //然后在保存t_user
        //设置user的logininfoId
//        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);


    }

    /**
     * 邮箱注册
     *  流程分析：
     *      输入邮箱账号
     *      输入密码
     *      再次输入密码
     *
     *  校验是否已经注册
     *      查询数据库，
     *  校验空值：
     *      邮箱，密码
     *  校验密码是否一致
     *  注册成功：为待激活状态--->仍处于未激活状态
     *
     *  注册成功后需要发送激活邮件
     *      需要对账号进行激活
     *      从待激活状态-->已激活状态
     *  注册失败直接弹窗提醒失败信息
     *      激活失败状态
     *
     */
    @Override
    public void registerEmail(UserDto userDto) throws MessagingException {
        //获取输入的邮箱和密码
        String email = userDto.getEmail();
        String pwd = userDto.getPassword();
        String confirmPwd = userDto.getPasswordRepeat();


        //进行校验
        //查询是否已经注册
         User userEmain = userMapper.findByEmail(email);
         if (userEmain != null){
             throw new BusinessException("该邮箱已经注册，请直接登录!");
         }
        //空值检验
        if (StringUtils.isEmpty(email)
                ||StringUtils.isEmpty(pwd)
                || StringUtils.isEmpty(confirmPwd)){
            throw new BusinessException("请输入正确的数据");
        }

        //密码判断
        if (!pwd.equals(confirmPwd)){
            throw  new BusinessException("两次密码不一致，请重新输入");
        }

        //获取logininfo对象
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);

        //保存到数据库 获取longininfo的自增长id
        logininfoMapper.add(logininfo);

        //拿去longininfoid用于传参激活
        Long logininfoId = logininfoMapper.findById(logininfo.getId()).getId();
        System.out.println(logininfoId);
        user.setLogininfoId(logininfoId);

        userMapper.add(user);

//        //保存审核日志
//        log.setState(2);
//        shopAuditLogMapper.add(log);

        //发送邮件
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //如果为true 能添加附件
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
        //发送人
        helper.setFrom("devil_osiris@qq.com");
        //邮件标题
        helper.setSubject("账号激活邮件");
        //true - 能够再内容中编写html标签 - 会解析
        helper.setText("<h3>你的账号已在宠物乐园平台注册成功，请<a href='http://localhost:8080/user/active/"+
                logininfoId+"'>点击这里</a>进行激活</h3>", true);

//        helper.setText("<h3>你的店铺已经审核通过，请<a href='http://localhost:8080/shop/active'>点击这里</a>激活邮件</h3>", true);


        helper.setTo(user.getEmail());

//        //发送
        javaMailSender.send(mimeMessage);
    }

    /**
     * 激活接口
     *
     *
     * 点击邮箱中的邮件链接 -----直接访问激活接口 ----
     * @param
     */
    @Override
    public void active(long id) {
        //查询到所处那过来的id对应的对象
        User user = userMapper.findByLogininfoId(id);

        Logininfo logininfo = logininfoMapper.findById(id);

        //修改所查找到对象的状态值字段
        user.setState(1);

        logininfo.setDisable(true);
        //修改对象
        userMapper.update(user);
        logininfoMapper.update(logininfo);
        //保存审核日志
//        shopAuditLog.setState(3);
//        shopAuditLogMapper.add(shopAuditLog);

    }

    private User userDto2User(UserDto userDto) {
        User user = new User();
        //手机激活
        if (user.getPhone()==null){
            user.setUsername(userDto.getPhone());
            user.setPhone(userDto.getPhone());
        }
        //邮箱激活
        if (user.getEmail()==null){
            user.setUsername(userDto.getEmail());
            user.setEmail(userDto.getEmail());
        }
        //随机加严
        String salt = StrUtils.getComplexRandomString(32);

        //获取加严后的密码继续加密
        String md5Pwd = Md5Utils.encrypByMd5(userDto.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //按照同名属性赋值(username email phone salt password)
        BeanUtils.copyProperties(user,logininfo);
        //当前对象是用户 设置type字段值

        logininfo.setType(1);
        return logininfo;
    }

    @Override
    @Transactional
    public void add(User user) {
        //加密加严
        //获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //获取加密之后的密码
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword()+salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        //设置自增长id
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.add(logininfo);
        super.add(user);
    }

    /**前端传过来的user是没有登陆信息id*/
    @Override
    @Transactional
    public void update(User user) {
        //加密加严
        //获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //获取加密之后的密码
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword()+salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        //用户user：createtime和logininfo_id不能修改
        //获取登录信息id
        Long logininfoId = userMapper.findById(user.getId()).getLogininfoId();
        //设置自增长id
        Logininfo logininfo = user2Logininfo(user);
        logininfo.setId(logininfoId);

        logininfoMapper.update(logininfo);
        super.update(user);
    }


    @Override
    @Transactional
    public void delete(Long id) {
        //获取登录信息的id
        Long logininfoId = userMapper.findById(id).getLogininfoId();
        //删除登录对象信息
        logininfoMapper.delete(logininfoId);
        super.delete(id);
    }
}
